package com.itany.crawler.proxy;

import com.itany.crawler.UrlBaseHandle;
import com.itany.crawler.Urls;
import com.itany.utils.Log;
import org.apache.http.HttpHost;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.HashMap;
import java.util.Map;

public class MyProxy extends UrlBaseHandle {
    static boolean proxyed = false;

    String url_proxy = "https://www.kuaidaili.com/free/intr/";
    public static Map<HttpHost, Integer> proxys = new HashMap<>();
    static Integer minNum = 30;
    static Integer maxNum = 30;
    static Integer modifyNum = 20; // 修改代理ip 数量

    public static int index = 0; //当前使用ip
    public static Integer nextPage = 1;

    // 链接失败 减 1 成功加 10 为0 删除
    static int deafult_weight = 20;

    // 前三页pproxiIP
    static int maxPageNum = 3;


    /**
     * 代理开启代理
     */
    public MyProxy() {
        setUrl(url_proxy + nextPage);
        nextPage %= maxPageNum;
        nextPage++;
    }

    public MyProxy(boolean proxyed) {
        super(proxyed);
        setUrl(url_proxy + nextPage);
        nextPage %= maxPageNum;
        nextPage++;
    }

    public String handle(Urls urls) throws Exception {
        String html = doGet();
        Document doc = Jsoup.parse(html, "UTF-8");

        try {
            Elements elements = doc.getElementsByClass("table-striped");
            elements.forEach(e -> {
                e.getElementsByTag("tbody").forEach(tb -> {
                    tb.getElementsByTag("tr").forEach(tr -> {
                        Elements tds = tr.getElementsByTag("td");
                        String ip = tds.get(0).text();
                        System.out.println("ip:" + ip);
                        Integer port = Integer.valueOf(tds.get(1).text());
                        System.out.println("port:" + port);
                        String scheme = tds.get(3).text();
                        System.out.println("scheme:" + scheme);

                        HashMap<HttpHost, Integer> host = new HashMap<>();
                        HttpHost hh = new HttpHost(ip, port, scheme);
                        proxys.put(hh, MyProxyManager.deafult_weight);
                    });
                });
            });
        } catch (Exception e) {
            Log.logErr("当前MyProxy.handle解析出错" + e.getMessage());
        }

        return "数据处理完毕";
    }

    // 是否是找代理时进行代理 防止循环调用调用 //正常为true
    static Boolean flag = true;

    public static HttpHost getHost() throws Exception {
        if (proxys.size() < minNum) {
//            minNum = modifyNum;
            synchronized (flag) {
                if (flag && proxys.size() < maxNum) {
                    Thread.sleep(10000);
                    flag = false;
                    try {
                        MyProxy myProxy = new MyProxy(proxyed);
                        System.out.println("开始添加代理IP");
                        myProxy.handle(null);
                        Log.logErr("添加代理成功");
                    } catch (Exception e) {
                        flag = true;
                        throw e;
                    }
                }
            }
        }
        HttpHost[] httpHosts = proxys.keySet().toArray(new HttpHost[0]);

        // 2147483647 int 最大值 短时间运行无需考虑
        return httpHosts[index++ % httpHosts.length];
    }


    /**
     * 成功加3
     */
    public static void incProxy(HttpHost hh) {
        Integer integer = proxys.get(hh);
        if (integer != null) {
            integer += 10;
            proxys.put(hh, integer);
        }
    }

    /**
     * 失败 -1
     */
    public static void decProxy(HttpHost hh) {
        Integer integer = proxys.get(hh);
        if (integer != null) {
            integer--;
            if (integer <= 0) {
                proxys.remove(hh);
            } else {
                proxys.put(hh, integer);
            }
        }
    }

    public static void main(String[] args) {
        MyProxy proxy = new MyProxy();
        //proxy.handle();

        proxys.forEach((k, v) -> System.out.println(k + " " + v));

    }
}
